<template>
  <el-dialog  title="选择位置" v-model="dialogVisible" :before-close="handleBeforeClose" @open="onOpen" @close="onClose" width="800px" append-to-body>
    <div class="box">
      <el-input
        id="searchInputId"
        class="common_layout"
        placeholder="输入关键词搜索位置"
        style="width: 36%"
        v-model="positionInput"
        @keyup.enter="searchLocation"
      />
      <el-button @click="searchLocation">搜索</el-button>
 
      <div class="list" v-if="addressList.length > 0">
        <div class="list_item" 
        :title="item.name" v-for="item in addressList" :key="item.id" @click="clickItem(item)">
          {{ item.name }}
        </div>
      </div>
    </div>
 
    <div class="gdmap_container">
      <div id="container" />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
 
<script setup>
import AMapLoader from "@amap/amap-jsapi-loader"
import { ref, watch, nextTick } from "vue"
import { ElMessage } from "element-plus"
 
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})
 
const $emit = defineEmits(["update:modelValue", "change"])
 
const dialogVisible = ref(props.modelValue)
watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
})

const handleBeforeClose = (done) => {
  $emit('update:modelValue', false)
  done()
}
 
const positionInput = ref("")
const addressList = ref([])
let map = null
let placeSearch = null
let geocoder = null
let marker = null
const selectedPosition = ref(null)
 
const onOpen = () => {
  nextTick(() => {
    initMap()
  })
}
 
const onClose = () => {
  if (map) {
    map.destroy()
    map = null
    placeSearch = null
    geocoder = null
    marker = null
    addressList.value = []
    positionInput.value = ""
    selectedPosition.value = null
  }
}
 
function initMap() {
  window._AMapSecurityConfig = {
    securityJsCode: "45489849db019ca4a46f941bdb4501c3"
  }
  AMapLoader.load({
    key: "df6abe0ff8f7b83e259fa74569e38456",
    version: "2.0",
    plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Geocoder"]
  }).then((AMap) => {
    if (document.getElementById('container')) {
      map = new AMap.Map("container", {
        resizeEnable: true,
        viewMode: "3D",
        zoom: 15
      })
      map.on("click", (e) => {
        const { lng, lat } = e.lnglat
        updateMarker(lng, lat)
        geocoder.getAddress([lng, lat], (status, result) => {
          let text=result.regeocode.formattedAddress ||"未知位置"
            selectedPosition.value = { address: text, lat, lng }
        })
      })
   
      const auto = new AMap.AutoComplete({ input: "searchInputId" })
   
      placeSearch = new AMap.PlaceSearch({
        pageSize: 20,
        map: map
      })

      geocoder = new AMap.Geocoder({
        city: "全国",
        radius: 1000
      })
   
      auto.on("select", (e) => {
        placeSearch.setCity(e.poi.adcode)
        placeSearch.search(e.poi.name)
      })
    }
  }).catch(e => {
    console.error("地图加载失败", e)
  })
}

function updateMarker(lng, lat) {
  if (marker) {
    map.remove(marker);
  }
  marker = new AMap.Marker({
    position: new AMap.LngLat(lng, lat),
  });
  map.add(marker);
}
 
const searchLocation = () => {
  if (!positionInput.value.trim()) {
    ElMessage.error("请输入搜索内容！")
    return
  }
  if (!placeSearch) {
    ElMessage.error("地图插件未加载，请稍后再试")
    return
  }
 
  placeSearch.search(positionInput.value, (status, result) => {
    if (status === "complete" && result.info === "OK") {
      if (result.poiList.pois.length > 0) {
        const poi = result.poiList.pois[0]
        map.setCenter([poi.location.lng, poi.location.lat])
        map.setZoom(15)
        addressList.value = result.poiList.pois
      } else {
        addressList.value = []
        ElMessage.error("未找到相关地点！")
      }
    } else {
      addressList.value = []
      ElMessage.error("搜索失败！")
    }
  })
}
 
const clickItem = (item) => {
  const { lng, lat } = item.location
  selectedPosition.value = {
    address: item.name,
    lat: lat,
    lng: lng
  }
  addressList.value=[]
  updateMarker(lng, lat)
  map.setCenter([lng, lat])
}

const handleConfirm = () => {
  if (selectedPosition.value) {
    $emit("change", selectedPosition.value)
  }
  $emit('update:modelValue', false)
}
 
const handleCancel = () => {
  $emit('update:modelValue', false)
}
</script>
 
<style scoped>
.box {
  position: relative;
  margin-bottom: 10px;
}
.list {
  z-index: 2000;
  position: absolute;
  top: 32px;
  left: 0;
  width: 36%;
  max-height: 260px;
  border: 1px solid #eee;
  overflow-y: auto;
  background-color: #fff;
}
 
.list_item {
  box-sizing: border-box;
  padding: 0 10px;
  line-height: 30px;
  overflow: hidden;
  white-space: nowrap;
  cursor: pointer;
  text-overflow: ellipsis;
  border-bottom: 1px solid #ccc;
}
.list_item:hover {
  background-color: #f5f5f5;
}
.gdmap_container {
  width: 100%;
  height: 400px;
}
#container {
  padding: 0px;
  margin: 0px;
  border: 1px solid gray;
  width: 100%;
  height: 100%;
}
</style>
